package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-17
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {

    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public void saveFollow(FollowBehaviorDto behaviorDto) {

        EntryDto entryDto = new EntryDto();

        entryDto.setEquipmentId(behaviorDto.getEquipmentId());

        entryDto.setUserId(behaviorDto.getUserId());

        ApBehaviorEntry entry = entryService.getEntry(entryDto);

        ApFollowBehavior followBehavior = new ApFollowBehavior();

        followBehavior.setEntryId(entry.getId());

        followBehavior.setCreatedTime(new Date());

        followBehavior.setOperation(behaviorDto.getOperation());

        followBehavior.setFollowId(behaviorDto.getFollowId());

        LambdaQueryWrapper<ApFollowBehavior> query = new LambdaQueryWrapper<>();

        query.eq(ApFollowBehavior::getEntryId, entry.getId());

        query.eq(ApFollowBehavior::getFollowId, behaviorDto.getFollowId());

        ApFollowBehavior one = this.getOne(query);

        if (one == null) {

            if (behaviorDto.getOperation() == 0) {

                this.save(followBehavior);
            }
        } else {

            if (one.getOperation() != behaviorDto.getOperation()) {

                one.setOperation(behaviorDto.getOperation());

                this.updateById(one);
            }
        }
    }
}
